import { initFormData } from "@/utils/init";
import { useBaseSearchForm } from "@/old-hooks/use-base-search-form"
import { useStoreMgShopStore } from "@/store/storeMg/shop";
import { useStoreMgSettlementStore } from "@/store/storeMg/settlement";
import message from "@/utils/message";

// storeName 映射pinia 
// baseModalFormRef 页面表单弹框dom
// modalFormData 页面表单弹框绑定值
// modalFormConfig 页面表单配置 为了初始化数据结构

export function useBaseModalForm(storeName, baseModalFormRef, basePageTableRef, modalFormData, modalFormConfig, modalCallBack = null) {

    let map = new Map();

    // pinia
    let storeMgShopStore = useStoreMgShopStore()
    let storeMgSettlementStore = useStoreMgSettlementStore()

    // 存入到数组中
    let mapList = [storeMgShopStore, storeMgSettlementStore]

    // 根据storeName 查找对应的pinia
    const mapValue = mapList.find((item) => item.$id === storeName);

    // 存入到map
    map.set(storeName, mapValue);

    // 新增按钮hook
    const createHook = () => {
        // 根据配置项 生成数据格式
        const form = initFormData(modalFormConfig.formItems)
        mapHook("create", form)
    }

    // 修改按钮hook
    const editHook = (row) => {
        const rowData = JSON.parse(JSON.stringify(row))
        mapHook("edit", rowData)
    }

    // 详情按钮hook
    const viewHook = (row) => {
        const rowData = JSON.parse(JSON.stringify(row))
        mapHook("view", rowData)
    }

    // 映射hook
    const mapHook = (name, row) => {
        // 赋值给弹框表单绑定的值
        modalFormData.value = row
        // 打开弹框
        baseModalFormRef.value.open()
        // 针对不同操作 callback出去
        modalCallBack && modalCallBack(name, row)
    }

    // 确认新增/编辑表格数据hook
    const confirmHook = (form) => {
        map.get(storeName).createAndUpdateTableData(form).then(res => {
            // 查询页面表格hook 保留查询条件
            searchHook()
            message.success("操作成功")
        }).catch(err => { })
    }

    // base-search-form 查询表格数据hook
    const { searchHook } = useBaseSearchForm(basePageTableRef)

    return { createHook, editHook, viewHook, confirmHook }
}